<template>
  <div class="gold-shop-wrap">
    <van-nav-bar title="申请退货" left-arrow fixed @click-left="onClickLeft" />
    <van-form @submit="onSubmit" class="aftet-sale-form">
      <div class="after-sales-title">退款类型</div>
      <van-field v-model="refundName" is-link readonly name="refundName" placeholder="请选择退货类型" @click="show = true"
        :rules="[{ required: true, message: '请选择退货类型' }]" />

      <div class="after-sales-title">退款原因</div>
      <van-field v-model="refundReasonName" is-link readonly name="refundReasonName" placeholder="请选择退款原因"
        @click="showReason = true" :rules="[{ required: true, message: '请选择退款原因' }]" />
      <div class="after-sales-title">问题描述</div>
      <!-- <van-field v-model="fieldValue" is-link readonly label="" placeholder="请输入退货的问题描述"
                :rules="[{ required: true, message: '请输入退货的问题描述' }]" /> -->
      <van-field v-model="refund_desc" rows="2" autosize name="refund_desc" label="" type="textarea" maxlength="300"
        placeholder="请输入退货的问题描述" :rules="[{ required: true, message: '请输入退货的问题描述' }]" show-word-limit />
      <div class="after-sales-title">上传凭证(最多6张)</div>
      <van-field name="voucher_urls" label="">
        <template #input>
          <van-uploader v-model="voucher_urls" multiple :max-count="6" :after-read="afterRead"
            :before-delete="uploadDlete" />
        </template>
      </van-field>
      <!-- <van-field name="uploader" label=""> -->
      <div class="after-sales-title">联系方式</div>
      <!-- </van-field> -->
      <van-field v-model="contact_name" name="contact_name" label="" placeholder="请输入联系人"
        :rules="[{ required: true, message: '请输入联系人' }]" />
      <van-field v-model="contact_phone" name="contact_phone" label="" placeholder="请输入联系电话"
        :rules="[{ required: true, message: '请输入联系电话' }, { validator: validatePhone, message: '请输入有效的手机号' }]" />
      <div class="aftersales_tip">
        温馨提示：
        <br>
        1.商品的退货审核结果可以在“我的-退款/售后”中查看审核结果
        <br>
        2.提交申请后，客服人员可能与您进行电话沟通，请保持手机畅通
        <br>
        3.退货成功后，退款将会原路返回至您的账户中，具体金额需要跟客服进行协商处理。
      </div>
      <div style="margin: 16px;">
        <van-button color="linear-gradient( 270deg, #1261E2 0%, #4A89EC 100%)" size="large" round
          native-type="submit">提交</van-button>
      </div>
    </van-form>
    <!-- 退款类型弹框 -->
    <van-popup v-model="show" position="bottom">
      <van-picker value-key="name" show-toolbar :columns="columns" @confirm="onConfirm" @cancel="show = false" />
    </van-popup>
    <!-- 原因 -->
    <van-popup v-model="showReason" position="bottom">
      <van-picker value-key="name" show-toolbar :columns="columnsReason" @confirm="onConfirmReason"
        @cancel="showReason = false" />
    </van-popup>
  </div>
</template>
<script>
import { getOssParams, uploadImage, uploadDelete } from '@/api/upload';
import {AFTER_SALES_CONFIG,AFTER_SALES_APPLY} from '@/api/mine'
import {OSS_TOKEN} from '@/api/cms'
export default {
  data() {
    return {
        fieldValue:'',
        radio:'1',
        fileList:[],
        value1:'',

        showReason:false,
        columnsReason:[],
        refundReasonName:"",
        refundReasonType:"",
        //
        columns:[],
        show:false,
        refundName:"",
        refundType:"",
        refund_desc:"",
        contact_name:"",
        contact_phone:"",
        voucher_urls:[],
        ossParams:null,
    };
  },
  mounted(){
      this.$http.get(AFTER_SALES_CONFIG+this.$route.query.id).then(res=>{
        this.columns=res.data.after_sales_type_list
      })
      // this.getOssParams()
  },
  methods: {
    async afterRead(file) {
  try {
    // 获取OSS上传参数
    if (!this.ossParams || this.ossParams.expire_time < Date.now()) {
      this.ossParams = await getOssParams(this.$http);
    }
    if (!this.ossParams) {
      throw new Error('OSS参数未正确设置');
    }
    // 调用封装的上传函数
    await uploadImage(file, this.ossParams, this.voucher_urls);
    console.log(this.voucher_urls);

  } catch (error) {
    console.error('处理上传错误:', error);
  }
},

uploadDlete(file) {
  this.voucher_urls = uploadDelete(file, this.voucher_urls);
},
  //   async getOssParams() {
  //     try {
  //       const response = await this.$http.get(OSS_TOKEN);
  //       if (response.data) {
  //         this.ossParams = response.data;
  //       } else {
  //         throw new Error('获取OSS参数失败');
  //       }
  //     } catch (error) {
  //       console.error('获取OSS参数错误:', error);
  //       throw error;
  //     }
  //   },
  //   async afterRead(file) {
  //     try {
  //       // 获取OSS上传参数
  //       if (!this.ossParams || this.ossParams.expire_time < Date.now()) {
  //         await this.getOssParams();
  //       }

  //       if (!this.ossParams) {
  //         throw new Error('OSS参数未正确设置');
  //       }

  //       // 创建FormData对象
  //       const formData = new FormData();
  //       formData.append('key', `${this.ossParams.path}/${file.file.name}`);
  //       formData.append('OSSAccessKeyId', this.ossParams.access_key_id);
  //       formData.append('policy', this.ossParams.policy);
  //       formData.append('Signature', this.ossParams.signature);
  //       formData.append('callback', this.ossParams.callback);
  //       formData.append('file', file.file);
  //       formData.append('success_action_status',200)

  //       // 发送上传请求
  //       const response = await fetch(this.ossParams.domain, {
  //         method: 'POST',
  //         body: formData
  //       });
  //       if(response.status==200){
  //         const url = `${this.ossParams.domain}/${this.ossParams.path}/${file.file.name}`;
  //     // 查找并更新现有项
  //     const index = this.voucher_urls.findIndex(item => item.file === file.file);
  //     if (index !== -1) {
  //       this.voucher_urls[index].url = url;
  //       this.voucher_urls[index].status = 'success';
  //     }
  //       }
  //     } catch (error) {
  //           console.error('上传错误:', error);
  //   // 标记上传失败
  //   const index = this.voucher_urls.findIndex(item => item.file === file.file);
  //   if (index !== -1) {
  //     this.voucher_urls[index].status = 'failed';
  //   }
  // }
  // },
  // uploadDlete(file){
  //   this.voucher_urls=this.voucher_urls.filter(item=>item.file.name!=file.file.name)
  // },
    showPopup() {
      this.show = true;
    },
    showPopupReason(){
      this.showReason=true
    },
    onConfirm(values) {
      console.log(values);
      this.refundName=values.name
      this.refundType=values.key
      this.show=false
      this.columnsReason=values.reasons
    },
    onConfirmReason(values){
      this.refundReasonName=values.name
      this.refundReasonType=values.key
      this.showReason=false
  },
    validatePhone(value) {
      // 简单的手机号正则校验
      const phoneRegex = /^1[3-9]\d{9}$/;
      return phoneRegex.test(value);
    },
    onClickLeft() {
            this.$router.back()
        },
        onConfirm(values){
          console.log(values);
          this.refundName=values.name
          this.refundType=values.key
          this.show=false
          this.columnsReason=values.reasons
        },
    onConfirmReason(values){
      this.refundReasonName=values.name
      this.refundReasonType=values.key
      this.showReason=false
    },
    onSubmit(values) {
      console.log('submit', values);
      let params={
        order_id:this.$route.query.id,
        refund_type:this.refundType,
        refund_reason:this.refundReasonName,
        refund_desc:this.refund_desc,
        contact_name:this.contact_name,
        contact_phone:this.contact_phone,
        voucher_urls:this.voucher_urls.map(item=>item.url)
      }
      this.$http.post(AFTER_SALES_APPLY,params).then(res=>{
        if(res.code==200){
          this.$toast.success('提交成功')
          this.$router.back()
      }
    })
    },
  },
};
</script>
<style lang="scss" scoped>
.gold-shop-wrap {
  min-height: 100vh;
  padding-top: 46px;
  background: #F2F4F5;

  ::v-deep .van-nav-bar .van-icon {
    color: #333333;
  }

  ::v-deep .van-nav-bar__arrow {
    font-size: 20px;
  }
}

.aftet-sale-form {
  width: 93%;
  margin: 0 auto;
}

.after-sales-title {
  padding-top: 0.2rem;
  width: 93%;
  margin: 0 auto;
  margin-bottom: 0.2rem;
  font-size: .28rem;
}

.aftersales_tip {
  font-size: 0.24rem;
  width: 95%;
  margin: 0 auto;
  color: #999;
  margin-top: 0.3rem;
  line-height: 0.4rem;
}
</style>
